﻿using System.Configuration;
using System.Text;
using MongoDB.Bson;
using MongoDB.Driver;
using Sustainalytics.LongRunningTaskManager;
using Sustainalytics.LongRunningTaskManager.Interface;
using Sustainalytics.MongoDB.Extensions;
using Sustainalytics.Synchronization.Validation.ValidationRules.Common;

namespace Sustainalytics.Insights.Tasks.Tasks
{
    internal class ValidationRulesWhiteListTask : ILongRunningTask
    {
        public LongRunningTaskTypeEnum Type
        {
            get { return LongRunningTaskTypeEnum.ValidationRulesWhiteListCSV; }
        }

        public object Start(LongRunningTaskContext context)
        {
            return GetFileResult();
        }

        private ILongRunningTaskResult GetFileResult()
        {
            var whiteList = MongoFactory.GetCollectionFromDatabase<WhiteList>(ConfigurationManager.ConnectionStrings["ValidationRules"].ConnectionString)
                .Find(new BsonDocument()).ToList();

            var fileContent = new StringBuilder();
            fileContent.AppendLine("Action,CapitalIqId,ResearchProduct");

            whiteList.ForEach(x => fileContent.AppendLine($"{string.Empty},{x.CapitalIqId},{x.ResearchProduct}"));

            return new LongRunningTaskFileInMemResult
            {
                EnforceInMemory = false,
                FileName = "whiteList.csv",
                MimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                Contents = Encoding.Default.GetBytes(fileContent.ToString())
            };
        }
    }
}
